<?php
// +----------------------------------------------------------------------
// | HkCms 后台首页
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: HkCms team <admin@hkcms.cn>
// +----------------------------------------------------------------------

declare (strict_types=1);

namespace app\admin\controller;

use libs\Tree;
use think\addons\Cloud;
use think\App;
use think\facade\Cache;
use think\facade\Db;

class Index extends BaseController
{
    protected $middleware = [
        'login',
        'auth' => ['except'=>['index','menu','profile','clearCache','getSystemInfo','upgrade','authorize']]
    ];

    public function index()
    {
        // 获取语言包列表
        $langs = Db::name('config')->where(['name'=>'admin_lang'])->value('data_list');
        $langs = json_decode($langs, true);

        $this->view->layout(false);
        $this->view->assign('langs', $langs);
        return $this->view->fetch();
    }

    /**
     * 首页面板
     * @return string|void
     */
    public function dashboard()
    {
        //快速导航
        $nav_list = Db::name('admin_panel')
                    ->alias('ap')
                    ->join('auth_rule ar','ap.auth_rule_id = ar.id')
                    ->where(['ap.admin_id'=>session('User.id'),'ar.status'=>'normal'])
                    ->field('ap.*,ar.name,ar.title,ar.route')
                    ->select();

        $assign = [
            'nav_list'    => $nav_list,
            'system_info' => $this->getSystemInfo()
        ];
        $this->view->assign($assign);
        return $this->view->fetch();
    }

    /**
     * 服务器信息
     * @return array
     */
    public function getSystemInfo()
    {
        return [
            'OS' => PHP_OS,
            'domain' => $this->request->rootDomain(),
            'running_system' => $this->request->server()['SERVER_SOFTWARE'],
            'phpv' => phpversion(),
            'mysqlv' => Db::query("SELECT VERSION() as mysqlv")[0]['mysqlv'],
            'gdv' => gd_info()['GD Version'],
        ];
    }

    /**
     * 个人资料
     * @return string|void
     */
    public function profile()
    {
        if ($this->request->isPost()) {
            $data = $this->request->only(['nickname'=>'','email'=>'','password'=>'']);
            if (!empty($data['password'])) {
                $data['salt'] = get_random_str();
                $data['password'] = $this->user->hashPassword($data['password'],$data['salt']);
            } else {
                unset($data['password']);
            }
            $result = Db::name('admin')->where(['id'=>$this->user->id])->save($data);
            if ($result) {
                foreach ($data as $k => $v) {
                    session('User.'.$k,$v);
                }
                $this->success();
            } else {
                $this->error(lang("Unchanged"));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 获取菜单
     */
    public function menu()
    {
        $this->view->layout(false);

        // $title = $this->request->param('title', '');
        // $map[] = ['status', '=', 'normal'];
        // if (!empty($title)) {
        //     $map[] = ['title', 'like', '%'.$title.'%'];
        // }

        $menu = Cache::get('Menu_'.$this->user->id);
        if (empty($menu)) {
            $menu = $this->user->getUserRules([['type','in','1,2']]);
            Cache::tag('menu')->set('Menu_'.$this->user->id, $menu);
        }
        $menu = Tree::instance()->init($menu)->getTreeArray(0);
        $this->view->assign('menu', $menu);
        $this->success('','',$this->view->fetch());
    }

    /**
     * 清空缓存
     */
    public function clearCache()
    {
        $type = $this->request->param('type', '');
        if ($type=='data') {
            $this->cache->clear();
            $this->success();
        } else if ($type=='log') {
            $pathArr = glob($this->app->getRootPath() . 'runtime' . DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR | GLOB_NOSORT);
            foreach ($pathArr as $key=>$value) {
                $pathTemp = glob($value . DIRECTORY_SEPARATOR. 'log' . DIRECTORY_SEPARATOR .'*', GLOB_ONLYDIR | GLOB_NOSORT);
                if (!empty($pathTemp)) {
                    foreach ($pathTemp as $k=>$v) {
                        \think\addons\Dir::instance()->delDir($v);
                    }
                }
            }
            $this->success();
        } else if ($type=='temp') {
            $pathArr = glob($this->app->getRootPath() . 'runtime' . DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR | GLOB_NOSORT);
            foreach ($pathArr as $key=>$value) {
                $pathTemp = $value . DIRECTORY_SEPARATOR. 'temp' . DIRECTORY_SEPARATOR;
                \think\addons\Dir::instance()->delFile($pathTemp);
            }
            $this->success();
        } else {
            $this->success(lang("Unknown operation"));
        }
    }

    /**
     * CMS检测更新
     */
    public function upgrade()
    {
        if ($this->request->isPost()) {
            $p = $this->request->param('p');
            $v = $this->request->param('v');
            ini_set('max_execution_time', '0');
            try {
                $res = Cloud::getInstance()->upgradeCms($v, $p);
            } catch (\Throwable $exception) {
                $this->error($exception->getMessage());
            }
            $this->success();
        }
        $v = $this->config->get('ver.cms_version');
        $p = $this->config->get('ver.cms_build');
        try {
            $res = Cloud::getInstance()->checkUpgrade($v, $p);
        } catch (\Throwable $exception) {
            $res = [];
        }

        if (empty($res)) {
            $this->error(lang('Server connection failed'),'',['upgrade'=>-1]);
        } else {
            $this->error('','',$res);
        }
    }

    /**
     * 联盟授权检测
     */
    public function authorize()
    {
        $domain = $this->request->host();
        try {
            $res = Cloud::getInstance()->checkAuthorize($domain);
        } catch (\Throwable $exception) {
            $res = [];
        }

        if (empty($res)) {
            $this->error(lang('Server connection failed'),'',['authorize'=>-1]);
        } else if (isset($res['authorize']) && $res['authorize']==1) {
            $this->success('','', ['authorize'=>1]);
        } else { // 未授权
            $this->error('','',$res);
        }
    }
}